<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="复制模板" @ok="handleSubmit">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, defineEmits, unref} from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { copyFormSchema } from './code.template.data';
  import { copyTemplate} from './code.template.api';
  import { listTemplateGroup } from '../code-template-group/code.template.group.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const sourceGroupId = ref("")
  const oldTemplateName = ref("")
  const emit = defineEmits(['register', 'success']);
  //表单配置
  const [registerForm, {resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    // labelWidth: 150,
    schemas: copyFormSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    oldTemplateName.value = data.name
    sourceGroupId.value = data.groupId
    const option = await listTemplateGroup({});
    await updateSchema({
      field: 'groupId',
      componentProps: {
        options: unref(option),
      },
    });
    //表单赋值
    await setFieldsValue({
      ...data,
    });
  });

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      if (values.name === oldTemplateName.value && values.groupId === sourceGroupId.value) {
        createMessage.error("同组下名称不能重复");
        return
      }
      
      setModalProps({ confirmLoading: true });
      //提交表单
      await copyTemplate({...values, sourceGroupId: sourceGroupId.value, targetGroupId: values.groupId});
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
